<?php


namespace App\Http\Rest\Shop\Resource;

use App\Exceptions\BusinessException;
use App\Http\Rest\Shop\BaseResource;
use App\Http\Rest\Shop\Model\ProductModel;
use App\Http\Rest\Shop\Model\RegionModel;
use App\Http\Rest\Shop\Service\AlipayService;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;

class SecondOrder
{
    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, $request)
    {
        $goods = $request->getIn('goods');
        $address = $request->getIn('address');

        $goodsId = $goods['second_hand_id'];

        $secondGoodsInfo = FDB::from('second_hand')
            ->where('second_hand_id', $goodsId)
            ->fetch();

        $orderParams['name'] = "二手物品";
        $orderParams['order_type'] = 3;
        $orderParams['order_no'] = time() . rand(1000, 9999);
        $orderParams['member_id'] = $request->getAttribute('member_id', 0);
        $orderParams['goods_amount'] = $secondGoodsInfo['price'];

        $orderGoods = [
            $goodsId => [
                'order_no' => $orderParams['order_no'],
                'quantity' => 1,
                'product_id' => $secondGoodsInfo['second_hand_id'],
                'product_name' => $secondGoodsInfo['product_name'],
                'product_thumbnail' => $secondGoodsInfo['product_thumbnail'],
                'price' => $secondGoodsInfo['price']
            ]
        ];

        $orderParams['total_amount'] = $orderParams['goods_amount'];
        $orderParams['message'] = $request->getIn('message', '');

        // 分享人
        $cookies = $request->getCookieParams();
        $orderParams['shared_by'] = $cookies['shared_by'] ?? 0;

        // 创建订单， 订单和商品关系
        $ret = call_user_func([BaseResource::class, 'resourceAdd'], 'order_base', $orderParams);
        if (!$ret) {
            throw new BusinessException("创建订单失败");
        }
        // 添加订单下的商品列表
        $ret2 = call_user_func([BaseResource::class, 'resourceAdd'], 'order_good', $orderGoods);

        // 添加订单收货地址
        $address['order_base_id'] = $ret;
        $address['member_id'] = $request->getAttribute('member_id', 0);
        $address['order_no'] = $orderParams['order_no'];
//        $regionModel = new RegionModel();
//        $address['province'] = $regionModel->getNameById($address['province_id']);
//        $address['city'] = $regionModel->getNameById($address['city_id']);
//        $address['area'] = $regionModel->getNameById($address['area_id']);
        $addressRet = call_user_func([BaseResource::class, 'resourceAdd'], 'order_address', $address);
        if (!$addressRet) {
            throw new BusinessException("创建收货地址失败");
        }

        return $orderParams;
    }
}
